from lxml import etree
from sets import Set
from APIExceptions import *
class DataNode(object):
    """
    This container contains the response data from webserver. Stored inside as lxml
    """
    def __init__(self,node,namespace=None):
        """
        Initialize with a DataContainer node or xml/html text.
        """
        myclass=node.__class__ 
        if myclass == self.__class__:
            #this is a Data container.
            self.data=node.data
            self.namespace=node.namespace
        elif myclass == etree._Element:
            self.data=node
            self.namespace=namespace
        elif myclass == str :
            self.data=etree.fromstring(node)
            self.namespace=namespace
            
    def setNamespace(self,namespace):
        self.namespace=namespace
    def getChildByName(self,tag):
        for child in self.data.iterchildren(self.namespace+tag):
            return (DataNode(child,self.namespace))
        raise KeyDoesNotExists("No such key exists")
    def getDescedentByName(self,tag):
        found=[]
        for child in self.data.iter(self.namespace+tag):
            found.append(DataNode(child,self.namespace))
        return found
    def getChildrenName(self):
        children=Set()
        for child in self.data.iterchildren():
            children.add(self.removeNamespaceFromTag(child.tag))
        return children
    def getDescedentsName(self):
        children=Set()
        for child in self.data.iter():
            children.add(self.removeNamespaceFromTag(child.tag))
        return children
    def removeNamespaceFromTag(self,string):
        string=string.split('}')
        return string[-1]
    def getAttr(self,attr):
        return getattr(self.data,attr)
    def str(self):
        if self.data.text:
            return self.data.text
        else :
            return etree.tostring(self.data)
    def __str__(self):
        if self.data.text:
            return self.data.text
        else :
            return "<%s.%s>" % (self.__class__.__name__,self.removeNamespaceFromTag(self.data.tag))
    def __repr__(self):
        if self.data.text:
            return self.data.text
        else :
            return "<%s.%s>" % (self.__class__.__name__,self.removeNamespaceFromTag(self.data.tag))
    def __eq__(self,string):
        if self.data.text == string :
            return True
        else:
            return False
    def __iter__(self):
        raise Exception("This object is not iteratable.")
    def __getattr__(self,tag):
        return self.getChildByName(tag)
    def __getitem__(self,tag):
        if type(tag) != str:
            raise Exception("Subscription must be string.")
        return self.getDescedentByName(tag)
